package com.burst.reptile.modular.api.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.burst.reptile.common.utils.SecurityUtils;
import com.burst.reptile.common.utils.ToolUtil;
import com.burst.reptile.framework.security.service.TokenService;
import com.burst.reptile.framework.web.controller.BaseController;
import com.burst.reptile.framework.web.result.LayuiResult;
import com.burst.reptile.modular.api.vo.MoreData;
import com.burst.reptile.modular.system.entity.SysUser;
import com.burst.reptile.modular.system.service.ISysUserService;
import com.burst.reptile.modular.zp.entity.ZpResources;
import com.burst.reptile.modular.zp.service.IZpResourcesService;
import com.burst.reptile.modular.zp.warpper.UserWrapper;
import com.burst.reptile.modular.zp.warpper.ZpResourcesWrapper;
import com.hankcs.hanlp.HanLP;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;

/**
 * 加载更多接口
 * @author wujin
 *
 * @date: 2020年6月18日 下午4:48:51
 */
@RestController
@RequestMapping("/loadmore")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ZpMoreController extends BaseController{
	
	private final IZpResourcesService resourcesService;
	
	private final ThymeleafViewResolver thymeleafViewResolver;
	
	private final ISysUserService userService;
	
	private final TokenService tokenService;
 
	/**
	 * 推荐加载更多
	 * @param page
	 * @param limit
	 * @return
	 */
	@GetMapping("/rec")
	public LayuiResult<Object> rec(@RequestParam(defaultValue = "2") Integer page, 
			@RequestParam(defaultValue = "10") Integer limit, 
			HttpServletRequest request, 
			HttpServletResponse response,
			Model model) {
		// 推荐文章
		Page<ZpResources> list = new Page<>();
		Page<ZpResources> pages = new Page<>(page, limit);
		ZpResources zpResources = new ZpResources();
		zpResources.setRec("1");
		zpResources.setColumnId(1); // 推荐铺友圈的
		zpResources.setDraft("0");
		zpResources.setCity(tokenService.getCitySite());
		if(SecurityUtils.isLogin()) {
			list = resourcesService.pageList(pages, zpResources);
			if(list.getTotal() == 0) {
				zpResources.setRec("0");
				list = resourcesService.pageList(pages, zpResources);
			}
		}else {
			list = resourcesService.pageList(pages, zpResources);
			if(list.getTotal() == 0) {
				zpResources.setRec("0");
				list = resourcesService.pageList(pages, zpResources);
			}
		}
		new ZpResourcesWrapper(list).wrap();
		boolean hasNext = list.hasNext();
		model.addAttribute("resourcesList", list.getRecords());
		model.addAttribute("hasNext", hasNext);
		WebContext ctx = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
		String html = thymeleafViewResolver.getTemplateEngine().process("common/index/content", ctx);
		return LayuiResult.success(list.getRecords().size(), MoreData.builder().hasNext(hasNext).res(html).build());
	}
	
	/**
	 * 推荐加载更多
	 * @param page
	 * @param limit
	 * @return
	 */
	@GetMapping("/h5/rec")
	public LayuiResult<Object> hrec() {
		// 推荐文章
		Page<ZpResources> list = new Page<>();
		Page<ZpResources> pages = startPage();
		ZpResources zpResources = new ZpResources();
		zpResources.setRec("1");
		zpResources.setColumnId(1); // 推荐铺友圈的
		zpResources.setDraft("0");
		zpResources.setCity(tokenService.getCitySite());
		if(SecurityUtils.isLogin()) {
			list = resourcesService.pageList(pages, zpResources);
			if(list.getTotal() == 0) {
				zpResources.setRec("0");
				list = resourcesService.pageList(pages, zpResources);
			}
		}else {
			list = resourcesService.pageList(pages, zpResources);
			if(list.getTotal() == 0) {
				zpResources.setRec("0");
				list = resourcesService.pageList(pages, zpResources);
			}
		}
		new ZpResourcesWrapper(list).wrap();
		return LayuiResult.success(list.getTotal(), list.getRecords());
	}
	
	/**
	 * 栏目加载更多
	 * @param id 栏目ID
	 * @param format 所属形态
	 * @param region 所在区域
	 * @param page 页数
	 * @param limit 获取数量
	 * @return
	 */
	@GetMapping("/column/{id}")
	public LayuiResult<Object> column(@PathVariable String id, 
			@RequestParam(required = false) String format,
			@RequestParam(required = false) String region,
			@RequestParam(required = false) String server,
			@RequestParam(defaultValue = "2") Integer page, 
			@RequestParam(defaultValue = "10") Integer limit,
			HttpServletRequest request, 
			HttpServletResponse response,
			Model model) {
		Page<ZpResources> pageList = new Page<>();
		Page<ZpResources> pages = new Page<>(page, limit);
		boolean hasNext = false;
		if(NumberUtil.isInteger(id)) {
			ZpResources resources = new ZpResources();
			resources.setCity(tokenService.getCitySite());
			resources.setDraft("0");
			if(StrUtil.isNotEmpty(format)) {
				resources.setFormatId(NumberUtil.parseInt(format));
			}
			if(StrUtil.isNotEmpty(region)) {
				resources.setCounty(region);
			}
			if(StrUtil.isNotEmpty(server)) {
				resources.setServiceItems(NumberUtil.parseInt(server));
			}
			resources.setColumnId(NumberUtil.parseInt(id));
			pageList = resourcesService.pageList(pages, resources);
			hasNext = pageList.hasNext();
		}
		new ZpResourcesWrapper(pageList).wrap();
		model.addAttribute("resourcesList", pageList.getRecords());
		model.addAttribute("hasNext", hasNext);
		WebContext ctx = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
		String html = thymeleafViewResolver.getTemplateEngine().process("common/index/content", ctx);
		return LayuiResult.success(pageList.getRecords().size(), MoreData.builder().hasNext(hasNext).res(html).build());
	}
	
	/**
	 * 栏目加载更多
	 * @param id 栏目ID
	 * @param format 所属形态
	 * @param region 所在区域
	 * @param page 页数
	 * @param limit 获取数量
	 * @return
	 */
	@GetMapping("/h5/column/{id}")
	public LayuiResult<Object> hcolumn(@PathVariable String id, 
			@RequestParam(required = false) String format,
			@RequestParam(required = false) String region,
			@RequestParam(required = false) String server
			) {
		Page<ZpResources> pageList = new Page<>();
		Page<ZpResources> pages = startPage();
		if(NumberUtil.isInteger(id)) {
			ZpResources resources = new ZpResources();
			resources.setCity(tokenService.getCitySite());
			resources.setDraft("0");
			if(StrUtil.isNotEmpty(format)) {
				resources.setFormatId(NumberUtil.parseInt(format));
			}
			if(StrUtil.isNotEmpty(region)) {
				resources.setCounty(region);
			}
			if(StrUtil.isNotEmpty(server)) {
				resources.setServiceItems(NumberUtil.parseInt(server));
			}
			resources.setColumnId(NumberUtil.parseInt(id));
			pageList = resourcesService.pageList(pages, resources);
		}
		new ZpResourcesWrapper(pageList).wrap();
		return LayuiResult.success(pageList.getTotal(), pageList.getRecords());
	}
	
	/**
	 * 搜索结果加载更多
	 * @param format 所属形态
	 * @param region 所在区域
	 * @param page 页数
	 * @param limit 获取数量
	 * @return
	 */
	@GetMapping("/search")
	public LayuiResult<Object> search(
			@RequestParam(required = false) String keyword,
			@RequestParam(defaultValue = "2") Integer page, 
			@RequestParam(defaultValue = "10") Integer limit,
			HttpServletRequest request, 
			HttpServletResponse response,
			Model model) {
		Page<ZpResources> pagelist = new Page<>();
		List<ZpResources> records = new ArrayList<>();
		if(StrUtil.isNotEmpty(keyword)) {
			List<String> ik = HanLP.extractKeyword(keyword, 3);
			pagelist = resourcesService.search(page, limit, keyword, ik);
			new ZpResourcesWrapper(pagelist).wrap();
			records = pagelist.getRecords();
			if(ToolUtil.isNotEmpty(records)) {
				records.forEach(i -> {
					String title = i.getTitle();
					String summary = i.getSummary();
					title = StrUtil.replace(title, keyword, "<span style='color:#ff4200;'>" + keyword + "</span>");
					summary = StrUtil.replace(summary, keyword, "<span style='color:#ff4200;'>" + keyword + "</span>");
					if(ToolUtil.isNotEmpty(ik)) {
						for (String str : ik) {
							title = StrUtil.replace(title, str, "<span style='color:#ff4200;'>" + str + "</span>");
							summary = StrUtil.replace(summary, str, "<span style='color:#ff4200;'>" + str + "</span>");
							if(str.matches(".*[a-zA-z].*")) {
								String swapCase = StrUtil.swapCase(str);
								title = StrUtil.replace(title, swapCase, "<span style='color:#ff4200;'>" + swapCase + "</span>");
								summary = StrUtil.replace(summary, swapCase, "<span style='color:#ff4200;'>" + swapCase + "</span>");
							}
						}
					}
					i.setTitle(title);
					i.setSummary(summary);
				});
			}
		}
		model.addAttribute("resourcesList", records);
		model.addAttribute("hasNext", pagelist.hasNext());
		WebContext ctx = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
		String html = thymeleafViewResolver.getTemplateEngine().process("common/index/searchContent", ctx);
		return LayuiResult.success(records.size(), MoreData.builder().hasNext(pagelist.hasNext()).res(html).build());
	}
	
	/**
	 * 搜索作者加载更多
	 * @param keyword 关键词
	 * @param page 页数
	 * @param limit 数量
	 * @param request
	 * @param response
	 * @param model
	 */
	@GetMapping("/searchAuth")
	public LayuiResult<Object> searchAuth(
			@RequestParam(required = false) String keyword,
			@RequestParam(defaultValue = "2") Integer page, 
			@RequestParam(defaultValue = "10") Integer limit,
			HttpServletRequest request, 
			HttpServletResponse response,
			Model model) {
		Page<SysUser> pagelist = new Page<>();
		List<SysUser> records = new ArrayList<>();
		if(StrUtil.isNotEmpty(keyword)) {
			List<String> ik = HanLP.extractKeyword(keyword, 3);
			pagelist = userService.search(page, limit, keyword, ik);
			new UserWrapper(pagelist).wrap();
			records = pagelist.getRecords();
			if(ToolUtil.isNotEmpty(records)) {
				records.forEach(i -> {
					String nickName = i.getNickName();
					nickName = StrUtil.replace(nickName, keyword, "<span style='color:#ff4200;'>" + keyword + "</span>");
					if(ToolUtil.isNotEmpty(ik)) {
						for (String str : ik) {
							nickName = StrUtil.replace(nickName, str, "<span style='color:#ff4200;'>" + str + "</span>");
							if(str.matches(".*[a-zA-z].*")) {
								String swapCase = StrUtil.swapCase(str);
								nickName = StrUtil.replace(nickName, swapCase, "<span style='color:#ff4200;'>" + swapCase + "</span>");
							}
						}
					}
					i.setNickName(nickName);
				});
			}
		}
		model.addAttribute("authorlist", records);
		model.addAttribute("keyword", keyword);
		model.addAttribute("hasNext", pagelist.hasNext());
		WebContext ctx = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
		String html = thymeleafViewResolver.getTemplateEngine().process("common/authorcontent", ctx);
		return LayuiResult.success(records.size(), MoreData.builder().hasNext(pagelist.hasNext()).res(html).build());
	}
	
	/**
	 * 加载用户文章列表
	 * @param userId 用户ID
	 * @param page 页数
	 * @param limit 获取数量
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@GetMapping("/res")
	public LayuiResult<Object> res(@RequestParam Long userId,
			@RequestParam(defaultValue = "2") Integer page, 
			@RequestParam(defaultValue = "20") Integer limit,
			HttpServletRequest request, 
			HttpServletResponse response,
			Model model) {
		Page<ZpResources> pagelist = new Page<>();
		Page<ZpResources> pages = new Page<>(page, limit);
		ZpResources resources = new ZpResources();
		resources.setUserId(userId);
		
		Page<ZpResources> pageList = resourcesService.pageList(pages, resources);
		new ZpResourcesWrapper(pageList).wrap();
		model.addAttribute("resourcesList", pageList.getRecords());
		model.addAttribute("hasNext", pageList.hasNext());
		WebContext ctx = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
		String html = thymeleafViewResolver.getTemplateEngine().process("common/user/contentInfo", ctx);
		return LayuiResult.success(pageList.getRecords().size(), MoreData.builder().hasNext(pagelist.hasNext()).res(html).build());
	}
	
}
